package com.example.broadcastapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class LocalBRActivity extends AppCompatActivity {
    /*②*/
    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_localbr);

        /*③借助localBroadcastManager管理本地广播*/
        localBroadcastManager = localBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter("com.example.broadcastapplication.LOCALBR");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);

        /*④利用Button点击事件发送本地广播*/
        Button btn_local = findViewById(R.id.btn_local);
        btn_local.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                localBroadcastManager = LocalBroadcastManager.getInstance(LocalBRActivity.this);
                Intent intent_local = new Intent("com.example.broadcastapplication.LOCALBR");
                localBroadcastManager.sendBroadcast(intent_local);
            }
        });

    }

    /*⑤Activity销毁时取消广播接收器的监听注册*/
    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    /*①创建本地广播接收器*/
    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Received in LocalReceiver!", Toast.LENGTH_SHORT).show();
        }
    }
}